import {types, Instance} from 'mobx-state-tree';
import { PopupScript } from '../pages/utils/connect';
const loginMap =  {
    'cd':'https://login-cd.xiaoshouyi.com/',
    'crm':'https://login.xiaoshouyi.com/'
}

export const loginStore = types.model('loginStore',{
    username: types.string,
    password: types.string,
    tenantId: types.number,
    port: types.number,
    env: types.string
})
.views(self=>{
    return {
        get loginUrl(){
            return loginMap[self.env];
        }
    }
})
.actions(self=>{
    return {
        changeLogin(key, value){
            self[key] = value;
        }
    }
})

export const webScocketLifeCycle = types.model('wsLifeCycle',{
    connectState: false
}).actions(self=>{
    return {
        changeState(state){
            self.connectState = state
        }
    }
})

export const MainStore = types.model('mainStore',{
    devHost: types.string,
    wsconfig:loginStore,
    wsLifeCycle:webScocketLifeCycle,
    cookie: types.maybe(types.string),
    mfSwitch: false
})
.actions(self=>{
    return {
        setMFSwitch(mfswitch){
            self.mfSwitch = mfswitch;
            PopupScript.send({
                type: 'mfswitch',
                data: {mfswitch: self.mfSwitch},
                cb: res => {
                    chrome.storage.sync.set({ "mfswitch" : self.mfSwitch }, function() {
                    });
                }
            })
        },
        toggleMfSwitch(){
            self.mfSwitch = !self.mfSwitch;
            PopupScript.send({
                type: 'mfswitch',
                data: {mfswitch: self.mfSwitch},
                cb: res => {
                    chrome.storage.sync.set({ "mfswitch" : self.mfSwitch }, function() {
                    });
                }
            })
        },
        setLoginConfig(key,value){
            self.wsconfig.changeLogin(key,value);
        },
        setLifeCycleState(state){
            self.wsLifeCycle.changeState(state)
        },
        setCookie(cookie){
            self.cookie = cookie;
        },
        cacheDevHost(){
            chrome.storage.sync.set({ "devHost" : self.devHost }, function() {
            });
        },
        setDevHost(devHost){
            self.devHost = devHost;
        },
    }
})

export type IMainStore = Instance<typeof MainStore>
export type IWebScocketLifeCycle = Instance<typeof webScocketLifeCycle>
export type ILoginStore = Instance<typeof loginStore>

export function createMainStore(){
    return MainStore.create({
        devHost:'https://127.0.0.1:4000',
        wsconfig:{
            username: '584666764@qq.com',
            password: "111111",
            tenantId: 1589281054818326,
            port: 4001,
            env: 'cd'   
        },
        wsLifeCycle:{
            connectState: false,
        },
        cookie:  undefined
    })
}